package com.guomei.service.curse.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.Certificate;
import com.guomei.bean.CourseSalesStats;
import com.guomei.bean.DataPanel;
import com.guomei.bean.User;
import com.guomei.bean.curse.*;
import com.guomei.bean.curse.vo.CourseDetail;
import com.guomei.bean.curse.vo.Stats;
import com.guomei.bean.user.vo.UserInfo;
import com.guomei.bean.work.domain.Work;
import com.guomei.bean.exam.domain.Exam;
import com.guomei.mapper.UserRoleMapper;
import com.guomei.mapper.curse.*;
import com.guomei.mapper.work.WorkMapper;
import com.guomei.mapper.CertificateMapper;
import com.guomei.mapper.UserMapper;
import com.guomei.service.curse.CourseService;
import com.guomei.utils.JwtUtil;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 课程服务实现类
 */
@Service
@Slf4j
@Transactional
public class CourseServiceImpl implements CourseService {
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private CourseChapterMapper courseChapterMapper;
    @Resource
    private CourseOrderMapper courseOrderMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Resource
    private CourseClassAssociationMapper courseClassAssociationMapper;
    @Resource
    private CourseVideoMapper courseVideoMapper;
    @Resource
    private UserCourseLearnMapper userCourseLearnMapper;
    @Resource
    private ExamMapper examMapper;
    @Resource
    private WorkMapper workMapper;
    @Resource
    private CourseCategoryMapper courseCategoryMapper;
    @Resource
    private CourseCategoryRelationMapper relationMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CertificateMapper certificateMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private DistributeRecordMapper distributeRecordMapper;
    
    @Override
    public Course getById(Long id) {
        if (id == null) {
            return null;
        }
        return courseMapper.selectById(id);
    }

    @Override
    public Course getByIdWithTeacher(Long id) {
        if (id == null) {
            return null;
        }
        return courseMapper.selectByIdWithTeacher(id);
    }

    @Override
    public List<Course> getAll() {
        return courseMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(Course course) {
        PageHelper.startPage(course.getPageNum(), course.getPageSize());
        List<Course> courses = courseMapper.selectByCondition(course);
        // 封装分页结果到PageData
        PageData<Course> pageData = new PageData<>();
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(course.getPageNum());
        pageData.setPageSize(course.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> getByConditionWithTeacher(Course course, HttpServletRequest request) {
        ArrayList<Integer> buyed = new ArrayList<>();
        // 从请求头中获取token
        String authHeader = request.getHeader("Authorization");
        log.info("Authorization Header: {}", authHeader);
        
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            log.info("提取的Token: {}", token);
        } else {
            log.warn("Authorization头格式不正确或为空: {}", authHeader);
        }
        
        Long userIdFromToken = null;
        if (token != null) {
            userIdFromToken = JwtUtil.getUserIdFromToken(token);
        }
        
        log.info("解析得到的用户ID: {}", userIdFromToken);
        // 只查询已支付的订单 (payStatus = 1)，未支付的订单不算已购买
        List<CourseOrder> courseOrders = courseOrderMapper.selectByUserId(userIdFromToken, (short) 1);
        List<Course> courses = courseMapper.selectCourseTypeIsOne();
        if (courses != null && !courses.isEmpty() && userIdFromToken != null){
            log.info("查询公开课数量：{}", courses.size());
            for (Course cours : courses) {
                //添加公开课
                buyed.add(cours.getId().intValue());
            }
        }
        if (courseOrders != null && !courseOrders.isEmpty()){
            log.info("查询已支付订单数量：{}（仅统计payStatus=1的订单）", courseOrders.size());
            for (CourseOrder courseOrder : courseOrders) {
                Long courseId = courseOrder.getCourseId();
                if (courseId != null) {
                    // 直接从CourseOrder中获取已购买的课程ID，不再查询CourseClassAssociation
                    buyed.add(courseId.intValue());
                    log.info("添加已支付课程ID：{} (payStatus={})", courseId, courseOrder.getPayStatus());
                }
            }
        }
        // 记录查询条件，包括status字段
        log.info("查询课程条件 - status: {}, courseType: {}, teacherId: {}, courseName: {}", 
                course.getStatus(), course.getCourseType(), course.getTeacherId(), course.getCourseName());
        
        PageHelper.startPage(course.getPageNum(), course.getPageSize());
        List<Course> coursesRes = courseMapper.selectByConditionWithTeacher(course);
        // 封装分页结果到PageData
        PageData<Course> pageData = new PageData<>();
        PageInfo<Course> pageInfo = new PageInfo<>(coursesRes);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(course.getPageNum());
        pageData.setPageSize(course.getPageSize());
        pageData.setBuyed(buyed);
        return Result.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(Course course) {
        if (course == null) {
            return Result.fail("课程信息不能为空");
        }
        CourseCategory courseCategory = null;
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        course.setCreatedTime(now);
        course.setUpdatedTime(now);

        // 设置默认值
        if (course.getStatus() == null) {
            course.setStatus((short) 0); // 默认草稿状态
        }
        if (course.getCanTry() == null) {
            course.setCanTry((short) 0); // 默认不支持试听
        }
        if (course.getDistributionRatio() == null) {
            course.setDistributionRatio(BigDecimal.ZERO);
        }
        if (course.getScore() == null) {
            course.setScore(BigDecimal.ZERO);
        }
        if (course.getStudentCount() == null) {
            course.setStudentCount(0);
        }
        course.setBingTime(LocalDateTime.now());
        if (course.getCategoryId() != null){
            courseCategory = courseCategoryMapper.selectById(course.getCategoryId());
            if (courseCategory == null){
                return Result.fail("课程分类不存在");
            }
        }

        if (courseMapper.insert(course) > 0){
            CourseCategoryRelation courseCategoryRelation = new CourseCategoryRelation();
            courseCategoryRelation.setCourseId(course.getId());
            courseCategoryRelation.setCategoryId(course.getCategoryId());
            relationMapper.insert(courseCategoryRelation);
            return Result.success(course);
        }

        return Result.fail("保存课程失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<Course> courses) {
        if (courses == null || courses.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Course course : courses) {
            // 设置创建和更新时间
            course.setCreatedTime(now);
            course.setUpdatedTime(now);

            // 设置默认值
            if (course.getStatus() == null) {
                course.setStatus((short) 0);
            }
            if (course.getCanTry() == null) {
                course.setCanTry((short) 0);
            }
            if (course.getDistributionRatio() == null) {
                course.setDistributionRatio(BigDecimal.ZERO);
            }
            if (course.getScore() == null) {
                course.setScore(BigDecimal.ZERO);
            }
            if (course.getStudentCount() == null) {
                course.setStudentCount(0);
            }
        }

        return courseMapper.batchInsert(courses) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(Course course) {
        if (course == null || course.getId() == null) {
            return Result.fail("课程信息不能为空");
        }

        if (course.getDistributionUserId() != null || course.getApproveId() != null) {
            Course course1 = courseMapper.selectById(course.getId());
            if (course1 != null) {
                course.setBingTime(LocalDateTime.now());
                if (course1.getDistributionUserId() != null && !course1.getDistributionUserId().isEmpty()) {
                    if (course.getEditType() != null && course.getEditType().equals("0")){
                        ArrayList<String> list = Arrays.stream(course1.getDistributionUserId().split(","))
                                .map(String::trim) // 去除可能的空格
                                .collect(Collectors.toCollection(ArrayList::new));
                        //判断是否传入的值是否包含在现有分销人员里内，在内的值则返回true
                        if (list.contains(course.getDistributionUserId())) {
                            log.info("分销用户id：{}已存在", course.getDistributionUserId());
                            return Result.fail("分销用户id已存在");
                        }
                        String[] split = course.getDistributionUserId().split(",");
                        list.addAll(Arrays.asList(split));
                        String string = String.join(",", list);
                        course.setDistributionUserId(string);
                    } else if (course.getEditType() != null && course.getEditType().equals("1")) {
                        String[] split = course.getDistributionUserId().split(",");
                        // 将split数组转换为List以便使用contains方法
                        List<String> splitList = Arrays.stream(split)
                                .map(String::trim)
                                .collect(Collectors.toList());

                        String result = Arrays.stream(course1.getDistributionUserId().split(","))
                                .map(String::trim)
                                // 过滤掉与split数组中相同的元素
                                .filter(id -> !id.isEmpty() && !splitList.contains(id))
                                .collect(Collectors.joining(","));
                        course.setDistributionUserId(result);
                    }else {
                        log.info("请求体内包含分销用户，但是没有选择编辑类型，不做任何处理");
                        return Result.fail("请求体内包含分销用户，但是没有选择编辑类型，不做任何处理");
                    }
                } else {
                    if (course.getEditType() != null && course.getEditType().equals("1")){
                        log.info("该课程没有任何分销用户，不做解绑处理");
                        return Result.fail("该课程没有任何分销用户，不做解绑处理");
                    }
                }
            }else {
                log.info("查询的课程不存在");
                return Result.fail("查询的课程不存在");
            }
        }
        if (course.getCategoryId() != null){
            CourseCategory courseCategory = courseCategoryMapper.selectById(course.getCategoryId());
            if (courseCategory == null){
                log.info("课程分类不存在");
                return Result.fail("课程分类不存在");
            }else {
                CourseCategoryRelation courseCategoryRelation = new CourseCategoryRelation();
                courseCategoryRelation.setCourseId(course.getId());
                courseCategoryRelation.setCategoryId(courseCategory.getId());
                relationMapper.deleteByCourseId(course.getId());
                relationMapper.insert(courseCategoryRelation);
            }
        }

        // 更新时间设为当前时间
        course.setUpdatedTime(LocalDateTime.now());

        return courseMapper.updateById(course) > 0 ? Result.success() : Result.fail("更新课程失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        boolean b = courseMapper.deleteById(id) > 0;
        boolean b1 = courseChapterMapper.deleteByCourseId(id) > 0;
        boolean b2 = courseVideoMapper.deleteByCourseId(id) > 0;
        return b;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return courseMapper.batchDelete(ids) > 0;
    }

    @Override
    public List<Course> getByCategoryId(Long categoryId) {
        if (categoryId == null) {
            return null;
        }
        return courseMapper.selectByCategoryId(categoryId);
    }

    @Override
    public List<Course> getByCategoryIdWithTeacher(Long categoryId) {
        if (categoryId == null) {
            return null;
        }
        return courseMapper.selectByCategoryIdWithTeacher(categoryId);
    }



//    @Override
//    public List<Course> getByCategoryIds(List<Long> categoryIds) {
//        if (categoryIds == null || categoryIds.isEmpty()) {
//            return new ArrayList<>();
//        }
//        return courseMapper.selectByCategoryIds(categoryIds);
//    }

    @Override
    public Result<CourseDetail> getCourseDetail(Long courseId, HttpServletRequest request) {

        if (courseId == null) {
            return Result.fail("课程ID不能为空");
        }
        
        Course course = courseMapper.selectByIdWithTeacher(courseId);
        if (course == null) {
            return Result.fail("课程不存在");
        }

        // 查询课程的章节信息（包含讲座）
        List<CourseChapter> chapters = courseChapterMapper.selectByCourseIdWithLectures(courseId);
        course.setChapters(chapters);

        // 检查用户是否已购买该课程
        boolean buyed = checkUserPurchasedCourse(courseId, request);
        course.setBuyed(buyed);
        
        // 查询课程绑定的考试信息
        List<Exam> exams = examMapper.selectByCourseId(courseId);

        List<Long> longs = relationMapper.selectCategoryIdsByCourseId(courseId);
        if (longs != null && !longs.isEmpty()){
            course.setCategory(courseCategoryMapper.selectById(longs.get(0)));
        }




        // 将 Course 对象转换为 CourseDetail 对象
        CourseDetail courseDetail = convertToCourseDetail(course);
        courseDetail.setExams(exams);
        
        log.info("课程详情查询成功: courseId={}, buyed={}, exams={}", courseId, buyed, exams != null ? exams.size() : 0);
        return Result.success(courseDetail);
    }
    
    /**
     * 将 Course 对象转换为 CourseDetail 对象
     */
    private CourseDetail convertToCourseDetail(Course course) {
        if (course == null) {
            return null;
        }
        
        CourseDetail courseDetail = new CourseDetail();
        courseDetail.setId(course.getId());
        courseDetail.setCourseName(course.getCourseName());
        courseDetail.setCoverImage(course.getCoverImage());
        courseDetail.setBannerImage(course.getBannerImage());
        courseDetail.setDescription(course.getDescription());
        courseDetail.setTeacherId(course.getTeacherId());
        courseDetail.setTeacher(course.getTeacher());
        courseDetail.setChapters(course.getChapters());
        courseDetail.setPrice(course.getPrice());
        courseDetail.setSalePrice(course.getSalePrice());
        courseDetail.setDiscountEndTime(course.getDiscountEndTime());
        courseDetail.setDuration(course.getDuration());
        courseDetail.setStatus(course.getStatus());
        courseDetail.setCourseType(course.getCourseType());
        courseDetail.setCanTry(course.getCanTry());
        courseDetail.setTryDuration(course.getTryDuration());
        courseDetail.setDistributionRatio(course.getDistributionRatio());
        courseDetail.setSuitablePeople(course.getSuitablePeople());
        courseDetail.setLearningProcess(course.getLearningProcess());
        courseDetail.setFaq(course.getFaq());
        courseDetail.setScore(course.getScore());
        courseDetail.setStudentCount(course.getStudentCount());
        courseDetail.setShareTitle(course.getShareTitle());
        courseDetail.setShareDescription(course.getShareDescription());
        courseDetail.setShareImage(course.getShareImage());
        courseDetail.setTryVideoUrl(course.getTryVideoUrl());
        courseDetail.setCreatedTime(course.getCreatedTime());
        courseDetail.setUpdatedTime(course.getUpdatedTime());
        courseDetail.setBuyed(course.getBuyed());
        courseDetail.setCourseMirrorUrl(course.getCourseMirrorUrl());
        courseDetail.setCategory(course.getCategory());
        courseDetail.setCourseMirrorImg(course.getCourseMirrorImg());
        
        return courseDetail;
    }
    
    /**
     * 检查用户是否已购买指定课程
     */
    private boolean checkUserPurchasedCourse(Long courseId, HttpServletRequest request) {
        try {
            // 检查是否为公开课（courseType = 1），公开课无需购买
            Course courseInfo = courseMapper.selectById(courseId);
            System.out.println("courseInfo: " + courseInfo);
            if (courseInfo != null && courseInfo.getCourseType() != null && courseInfo.getCourseType() == 1) {
                log.info("公开课无需购买: courseId={}", courseId);
                return true;
            }
            
            // 从请求头中获取token
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                log.info("未登录用户查询收费课程详情: courseId={}", courseId);
                return false;
            }
            
            String token = authHeader.substring(7);
            Long userIdFromToken = JwtUtil.getUserIdFromToken(token);
            
            if (userIdFromToken == null) {
                log.warn("Token解析失败，无法获取用户ID");
                return false;
            }
            
            // 直接查询用户是否有该课程的已支付订单
            CourseOrder courseOrder = courseOrderMapper.selectByUserIdAndCourseId(userIdFromToken, courseId);
            
            System.out.println("courseOrder: " + courseOrder);
            if (courseOrder != null) {
                log.info("用户已购买课程: userId={}, courseId={}", userIdFromToken, courseId);
                return true;
            }
            
            log.info("用户未购买课程: userId={}, courseId={}", userIdFromToken, courseId);
            return false;
            
        } catch (Exception e) {
            log.error("检查用户购买状态失败: courseId={}", courseId, e);
            return false;
        }
    }

    @Override
    public Result<?> CountByCourseAndUserId(CountByCourseAndUserIdDTO countByCourseAndUserIdDTO) {
        //统计课程全部视频数
        Long countCourseNumber = 0L;
        //统计已完成课程数
        Long countFinishedCourseNumber = 0L;
        //统计观看时长 分钟
        Long countWatchTime = 0L;
        List<CourseVideo> courseVideos = courseVideoMapper.selectByCourseId(countByCourseAndUserIdDTO.getCourseId());
        if (courseVideos != null && !courseVideos.isEmpty()){
            countCourseNumber = Long.valueOf(courseVideos.size());
        }
        List<UserCourseLearn> userCourseLearns = userCourseLearnMapper.selectByUserAndCourse(countByCourseAndUserIdDTO.getUserId(), countByCourseAndUserIdDTO.getCourseId());
        if (userCourseLearns != null && !userCourseLearns.isEmpty()){
            for (UserCourseLearn userCourseLearn : userCourseLearns) {
                if (userCourseLearn != null && userCourseLearn.getStatus() == 1){
                    countFinishedCourseNumber++;
                }
                if (userCourseLearn != null && userCourseLearn.getLearnDuration() != null){
                    // 将秒转换为分钟（向上取整）
                    countWatchTime += (userCourseLearn.getLearnDuration() + 59) / 60;
                }
            }
        }
        CountByCourseAndUserIdResponse countByCourseAndUserIdResponse = new CountByCourseAndUserIdResponse();
        countByCourseAndUserIdResponse.setCountCourseNumber(countCourseNumber);
        countByCourseAndUserIdResponse.setCountFinishedCourseNumber(countFinishedCourseNumber);
        countByCourseAndUserIdResponse.setCountWatchTime(countWatchTime);
        return Result.success(countByCourseAndUserIdResponse);
    }
    
    @Override
    public Result<Stats> getCourseLearnStats(Long userId) {
        try {

            Stats stats = new Stats();
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            
            log.info("开始统计用户课程学习信息: userId={}", userId);
            
            
            // 2. 统计用户开始学习的课程数量
            Long totalStartedCourses = userCourseLearnMapper.countStartedCoursesByUserId(userId);
            log.debug("用户{}开始学习的课程数量: {}", userId, totalStartedCourses);
            
            // 3. 统计进度为100%的记录数量（已完成的视频数量）
            Long completedVideos = userCourseLearnMapper.countCompletedVideosByUserId(userId);
            log.debug("用户{}已完成的视频数量: {}", userId, completedVideos);

            // 统计用户已学完的课程数量
            Long totalFinishedCourses = userCourseLearnMapper.countFinishedCoursesByUserId(userId);
            log.debug("用户{}已学完的课程数量: {}", userId, totalFinishedCourses);
            
            // 4. 统计总学习时长（秒）
            Long totalLearnDuration = userCourseLearnMapper.sumLearnDurationByUserId(userId);
            log.debug("用户{}总学习时长(秒): {}", userId, totalLearnDuration);
            
            // 5. 统计证书数量
            QueryWrapper<Certificate> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            Long totalCertificateNumber = certificateMapper.selectCount(wrapper);
            log.debug("用户{}证书数量: {}", userId, totalCertificateNumber);
            
            QueryWrapper<Work> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            Long workNumber = workMapper.selectCount(queryWrapper);
            log.debug("用户{}作业数量: {}", userId, workNumber);
            
            stats.setWorkNumber(workNumber);
            stats.setTotalStartedCourses(totalStartedCourses);
            stats.setCompletedVideos(completedVideos);
            stats.setTotalLearnDuration(totalLearnDuration);
            stats.setTotalLearnDurationMinutes(totalLearnDuration / 60);
            stats.setTotalLearnDurationHours(totalLearnDuration / 3600);
            stats.setTotalLearnDurationDays(totalLearnDuration / 86400);
            stats.setTotalLearnDurationMonths(totalLearnDuration / 2592000);
            stats.setTotalLearnDurationYears(totalLearnDuration / 31536000);
            stats.setTotalCertificateNumber(totalCertificateNumber);
            
            return Result.success(stats);
            
        } catch (Exception e) {
            log.error("获取用户课程学习统计信息失败: userId={}", userId, e);
            return Result.fail("获取学习统计信息失败: " + e.getMessage());
        }
    }

    @Override
    public Result<?> selectDistributionList(Course  course) {
        List<Long> UserIds = new ArrayList<>();
        Course course1 = courseMapper.selectById(course.getId());
        if (course1 == null){
            return Result.fail("课程不存在");
        }
        if (course.getTeacherType().equals("0")){
            if (course1.getDistributionUserId() == null || course1.getDistributionUserId().isEmpty()){
                return Result.success("课程不存在分销人员，不进行查询");
            }else {
                UserIds = Arrays.stream(course1.getDistributionUserId().split(","))
                        .map(String::trim)
                        .map(Long::parseLong)
                        .collect(Collectors.toCollection(ArrayList::new));
            }
        }
        PageHelper.startPage(course.getPageNum(), course.getPageSize());
        List<User> users = userMapper.selectByAll(UserIds);
        for (User user : users){
            user.setBingTime(course1.getBingTime());
        }
        // 封装分页结果到PageData
        PageData<User> pageData = new PageData<>();
        PageInfo<User> pageInfo = new PageInfo<>(users);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(course.getPageNum());
        pageData.setPageSize(course.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> getDataPanel() {
        DataPanel dataPanel = new DataPanel();
        //获取本月第一天0点时间
        LocalDateTime firstDayOfMonth = LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
        //统计用户数
        User user = new User();
        //获取今日0点时间，创建时间字段的
        // 将LocalDateTime转换为Date类型
        Date todayStartTime = Date.from(LocalDateTime.of(LocalDate.now(), LocalTime.MIN)
                .atZone(ZoneId.systemDefault()).toInstant());
        user.setCreatedTime(todayStartTime);
        int countUsers = userMapper.count(null);
        int todayInsertCountUsers = userMapper.count(user);
        dataPanel.setCountUsers(countUsers);
        dataPanel.setTodayInsertCountUsers(todayInsertCountUsers);
        //统计订单数
        CourseOrder courseOrder1 = new CourseOrder();
        courseOrder1.setOrderStatus((short) 0);
        List<CourseOrder> courseOrders = courseOrderMapper.selectByCondition(courseOrder1);
        int countOrders = courseOrderMapper.count();
        int countNoPayOrders = courseOrderMapper.notPayCount();
// 过滤本月订单
        List<CourseOrder> monthlyOrders = courseOrders.stream()
                .filter(courseOrder -> courseOrder.getCreatedTime() != null &&
                        (courseOrder.getCreatedTime().isAfter(firstDayOfMonth) || courseOrder.getCreatedTime().isEqual(firstDayOfMonth)))
                .collect(Collectors.toList());

// 统计本月实付金额
        BigDecimal monthlyIncome = monthlyOrders.stream()
                .map(CourseOrder::getPayAmount)  // 假设字段名为actualPayment
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

// 同时统计今日收入（如果需要）
        LocalDateTime todayLocalStartTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        List<CourseOrder> todayOrders = monthlyOrders.stream()
                .filter(order -> order.getCreatedTime() != null &&
                        (order.getCreatedTime().isAfter(todayLocalStartTime) || order.getCreatedTime().isEqual(todayLocalStartTime)))
                .collect(Collectors.toList());

        BigDecimal todayIncome = todayOrders.stream()
                .map(CourseOrder::getPayAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

// 统计实付总金额
        BigDecimal totalActualPayment = courseOrders.stream()
                .map(CourseOrder::getPayAmount)  // 使用实际支付金额字段
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

// 统计招生用户人数（去重统计不同用户）
        long enrolledUserCount = courseOrders.stream()
                .map(CourseOrder::getUserId)
                .filter(Objects::nonNull)
                .distinct()
                .count();
        dataPanel.setCountOrders(countOrders);
        dataPanel.setCountNoPayOrders(countNoPayOrders);
        dataPanel.setThisMonthIncome(monthlyIncome);
        dataPanel.setTodayIncome(todayIncome);
        dataPanel.setCountEnrollUsers(enrolledUserCount);
        dataPanel.setCountEnrollIncome(totalActualPayment);
//统计招生老师数量
        int i = userRoleMapper.countTeacher();
        dataPanel.setCountEnrollTeachers(i);
// 统计招生老师订单数和相应金额
        long enrollTeacherOrderCount = courseOrders.stream()
                .filter(order -> order.getDistributionUserId() != null && !order.getDistributionUserId().isEmpty())
                .count();

        BigDecimal enrollTeacherOrderAmount = courseOrders.stream()
                .filter(order -> order.getDistributionUserId() != null && !order.getDistributionUserId().isEmpty())
                .map(CourseOrder::getPayAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
// 按日期分组统计每日订单数和收入
        Map<LocalDate, Long> dailyOrderCount = courseOrders.stream()
                .filter(order -> order.getCreatedTime() != null)
                .collect(Collectors.groupingBy(
                        order -> order.getCreatedTime().toLocalDate(),
                        Collectors.counting()
                ));

        Map<LocalDate, BigDecimal> dailyIncome = courseOrders.stream()
                .filter(order -> order.getCreatedTime() != null && order.getPayAmount() != null)
                .collect(Collectors.groupingBy(
                        order -> order.getCreatedTime().toLocalDate(),
                        Collectors.reducing(BigDecimal.ZERO, CourseOrder::getPayAmount, BigDecimal::add)
                ));


// 设置到dataPanel中
        dataPanel.setOrderTrend(dailyOrderCount);
        dataPanel.setIncomeTrend(dailyIncome);
// 设置到dataPanel中
        dataPanel.setCountEnrollTeacherOrders(enrollTeacherOrderCount);
        dataPanel.setCountEnrollTeacherIncome(enrollTeacherOrderAmount);

// 按课程ID分组统计销量最高的前5个课程
        List<CourseSalesStats> topCourses = courseOrders.stream()
                .filter(order -> order.getCourseId() != null && order.getPayAmount() != null)
                .collect(Collectors.groupingBy(CourseOrder::getCourseId))
                .entrySet().stream()
                .map(entry -> {
                    Long courseId = entry.getKey();
                    List<CourseOrder> orders = entry.getValue();

                    // 计算该课程的总收入
                    BigDecimal totalAmount = orders.stream()
                            .map(CourseOrder::getPayAmount)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 计算报名人数（去重）
                    long enrollCount = orders.stream()
                            .map(CourseOrder::getUserId)
                            .filter(Objects::nonNull)
                            .distinct()
                            .count();
                    Course course = courseMapper.selectById(courseId);
                    CourseSalesStats stats = new CourseSalesStats();
                    stats.setCourseId(courseId);
                    stats.setTotalAmount(totalAmount);
                    stats.setEnrollCount(enrollCount);
                    if (course != null && course.getCourseName() != null)
                        stats.setCourseName(course.getCourseName());
                    return stats;
                })
                .sorted((s1, s2) -> s2.getTotalAmount().compareTo(s1.getTotalAmount())) // 按金额降序排序
                .limit(5) // 取前5个
                .collect(Collectors.toList());


        dataPanel.setHotCourseRank(topCourses);
        return Result.success(dataPanel);
    }

    @Override
    public Result<?> getCourseListWithStats(com.guomei.bean.curse.dto.CourseStatsQueryDTO queryDTO) {
        try {
            if (queryDTO == null || queryDTO.getPageNum() == null || queryDTO.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            
            // 验证分页参数是否有效
            if (queryDTO.getPageNum() <= 0 || queryDTO.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            
            log.info("查询课程统计列表，参数：pageNum={}, pageSize={}, courseName={}, status={}, courseType={}", 
                    queryDTO.getPageNum(), queryDTO.getPageSize(), queryDTO.getCourseName(), 
                    queryDTO.getStatus(), queryDTO.getCourseType());
            
            // 使用 PageHelper 进行分页
            PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
            
            // 执行查询
            List<com.guomei.bean.curse.vo.CourseWithStats> list = courseMapper.selectCourseWithStats(
                    queryDTO.getCourseName(),
                    queryDTO.getStatus(),
                    queryDTO.getCourseType()
            );
            
            // 封装分页结果
            PageInfo<com.guomei.bean.curse.vo.CourseWithStats> pageInfo = new PageInfo<>(list);
            PageData<com.guomei.bean.curse.vo.CourseWithStats> pageData = new PageData<>();
            pageData.setTotal(pageInfo.getTotal());
            pageData.setData(pageInfo.getList());
            pageData.setPageNum(queryDTO.getPageNum());
            pageData.setPageSize(queryDTO.getPageSize());
            
            log.info("查询课程统计列表成功，共 {} 条记录", pageInfo.getTotal());
            
            return Result.success(pageData);
            
        } catch (Exception e) {
            log.error("查询课程统计列表失败", e);
            return Result.fail("查询课程统计列表失败: " + e.getMessage());
        }
    }

    @Override
    public Result<?> getDistributorCourseList(com.guomei.bean.curse.dto.DistributorCourseListDTO dto) {
        try {
            if (dto == null || dto.getPageNum() == null || dto.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            
            if (dto.getTeacherId() == null) {
                return Result.fail("教师ID不能为空");
            }
            
            // 验证分页参数是否有效
            if (dto.getPageNum() <= 0 || dto.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            
            log.info("查询分销课程列表，参数：teacherId={}, pageNum={}, pageSize={}, courseName={}, status={}, courseType={}", 
                    dto.getTeacherId(), dto.getPageNum(), dto.getPageSize(), dto.getCourseName(), 
                    dto.getStatus(), dto.getCourseType());
            
            // 使用 PageHelper 进行分页
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            
            // 执行联表查询
            // 查询逻辑：查询所有符合条件的课程，如果课程有该teacherId的分销关系则一起返回，没有则courseDistributerRel为null
            List<com.guomei.bean.curse.vo.CourseDistribute> list = courseMapper.selectDistributorCourseList(dto);
            
            // 封装分页结果
            PageInfo<com.guomei.bean.curse.vo.CourseDistribute> pageInfo = new PageInfo<>(list);
            PageData<com.guomei.bean.curse.vo.CourseDistribute> pageData = new PageData<>();
            pageData.setTotal(pageInfo.getTotal());
            pageData.setData(pageInfo.getList());
            pageData.setPageNum(dto.getPageNum());
            pageData.setPageSize(dto.getPageSize());
            
            log.info("查询分销课程列表成功，共 {} 条记录", pageInfo.getTotal());
            
            return Result.success(pageData);
            
        } catch (Exception e) {
            log.error("查询分销课程列表失败", e);
            return Result.fail("查询分销课程列表失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<Boolean> checkCoursePurchaseStatus(Long userId, List<Long> courseIds) {
        List<Boolean> purchaseStatus = new ArrayList<>();
        
        if (userId == null || courseIds == null || courseIds.isEmpty()) {
            log.warn("检查课程购买状态参数不完整: userId={}, courseIds={}", userId, courseIds);
            // 返回与courseIds长度相同的false数组
            if (courseIds != null) {
                for (int i = 0; i < courseIds.size(); i++) {
                    purchaseStatus.add(false);
                }
            }
            return purchaseStatus;
        }
        
        try {
            // 1. 查询用户已购买的课程ID列表（包括公开课和付费课程）
            List<Long> purchasedCourseIds = new ArrayList<>();
            
            // 1.1 获取公开课列表（courseType = 1）
            List<Course> publicCourses = courseMapper.selectCourseTypeIsOne();
            if (publicCourses != null && !publicCourses.isEmpty()) {
                for (Course course : publicCourses) {
                    if (course.getId() != null) {
                        purchasedCourseIds.add(course.getId());
                    }
                }
            }
            
            // 1.2 获取用户已支付的课程订单
            List<CourseOrder> courseOrders = courseOrderMapper.selectByUserId(userId, (short) 1); // payStatus = 1 表示已支付
            if (courseOrders != null && !courseOrders.isEmpty()) {
                for (CourseOrder order : courseOrders) {
                    if (order.getCourseId() != null) {
                        purchasedCourseIds.add(order.getCourseId());
                        
                        // 如果是专研班或专修班，还需要添加其下属课程
                        Course course = courseMapper.selectById(order.getCourseId());
                        if (course != null && course.getCourseType() != null && 
                            (course.getCourseType() == 3 || course.getCourseType() == 4)) {
                            List<CourseClassAssociation> associations = courseClassAssociationMapper.selectByMainCourseId(course.getId());
                            if (associations != null && !associations.isEmpty()) {
                                for (CourseClassAssociation association : associations) {
                                    if (association.getDeputyCourseId() != null) {
                                        purchasedCourseIds.add(association.getDeputyCourseId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            // 2. 检查每个课程是否在已购买列表中
            for (Long courseId : courseIds) {
                boolean isPurchased = purchasedCourseIds.contains(courseId);
                purchaseStatus.add(isPurchased);
                
                log.debug("课程购买状态检查: userId={}, courseId={}, isPurchased={}", userId, courseId, isPurchased);
            }
            
            log.info("课程购买状态检查完成: userId={}, 检查课程数={}, 已购买课程数={}", 
                userId, courseIds.size(), purchasedCourseIds.size());
            
            return purchaseStatus;
            
        } catch (Exception e) {
            log.error("检查课程购买状态失败: userId={}, courseIds={}", userId, courseIds, e);
            // 发生异常时返回false数组
            for (int i = 0; i < courseIds.size(); i++) {
                purchaseStatus.add(false);
            }
            return purchaseStatus;
        }
    }
}
